/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.deployment.dao;

import br.com.deployment.entity.orcamento.Orcamento;
import br.com.deployment.daogenerico.DaoGenerico;
import br.com.deployment.interfaces.OrcamentoDaoIn;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.Query;

/**
 *
 * @author elyjr
 */
@Stateless
@LocalBean
public class OrcamentoDao extends DaoGenerico<Orcamento> implements OrcamentoDaoIn{
    
    public OrcamentoDao(){
        super(Orcamento.class);
    }
    
    public Orcamento salvar(Orcamento entity) {
        getEm().persist(entity);
        return find(entity.getId());
    }
    
    @Override
    public boolean exist(int id){
        String sql = "Select o from Orcamento o where o.id = :id";
        Query query = getEm().createQuery(sql);
        query.setParameter("id", id);
        
        try{
             query.getSingleResult();
        }catch(NoResultException nr){
            return true;
        }
        return false;
    }
    
    @Override
    public List<Orcamento> pesquisar(Orcamento orc, Integer cod){
        String sql = "";
        sql += "Select o from Orcamento o where";
        
        if(cod != null){
            sql += " o.id = :cod and ";
        }
        if (orc.getDoc() != null && orc.getDoc().length() > 0) {
            sql += " lower(o.doc) like lower(:doc) and ";
        }
        if (orc.getNome() != null && orc.getNome().length() > 0) {
            sql += " lower(o.nome) like lower(:interessado) and ";
        }
        if (orc.getDataCadastro() != null) {
            sql += " o.dataCadastro = :data and ";
        }
        
        sql += " 1 = 1 ORDER BY o.id DESC";
                
        Query query = getEm().createQuery(sql);
        
        if(cod != null){
            query.setParameter("cod", cod);
        }
        if (orc.getDoc() != null && orc.getDoc().length() > 0) {
            query.setParameter("doc", "%"+orc.getDoc()+"%");
        }
        if (orc.getNome() != null && orc.getNome().length() > 0) {
            query.setParameter("interessado", "%"+orc.getNome()+"%");
        }
        if (orc.getDataCadastro() != null) {
            query.setParameter("data", orc.getDataCadastro());
        }
        System.err.println(sql);
         
        return query.getResultList();
    }
}
